﻿using System;
using System.Collections.Generic;
using System.Reflection;
using System.Runtime.InteropServices;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;

namespace PluginDependencyTest
{
    public class NativeMethods
    {
        // 使用Unicode版本(LoadLibraryW)
        [DllImport("kernel32.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern IntPtr LoadLibraryW(string lpFileName);

        [DllImport("kernel32.dll", SetLastError = true)]
        [return: MarshalAs(UnmanagedType.Bool)]
        public static extern bool FreeLibrary(IntPtr hModule);

        [DllImport("kernel32.dll", CharSet = CharSet.Ansi, SetLastError = true)]
        public static extern IntPtr GetProcAddress(IntPtr hModule, string lpProcName);
    }


    public class DllAnalyzer
    {

        public static void Analysis(TextBox tb)
        {
            List<AssemblyName> dlls = AssemblyAnalyzer.ParseAssemblyNames(tb.Text);
            List<string> dllNams = new List<string>();

            StringBuilder sb = new StringBuilder();
            sb.AppendLine("解析结果：");
            sb.AppendLine();
            foreach (var lib in dlls)
            {
                sb.AppendLine(lib.ToString());
                dllNams.Add(lib.Name);
            }
            sb.AppendLine();
            sb.Append(Analysis(dllNams));

            tb.Text = sb.ToString();
        }

        public static string Analysis(List<string> dlls)
        {
            StringBuilder sb = new StringBuilder();
            
            foreach (var dll in dlls)
            {
                var path = dll;
                if (!path.EndsWith(".dll"))
                    path += ".dll";

                if (dll.StartsWith("System.") ||
                    dll.StartsWith("Microsoft.") ||
                    dll.StartsWith("api-ms-win") ||
                    dll.StartsWith("vcruntime") ||
                    dll.StartsWith("msvc") ||
                    AssemblyAnalyzer.windowsDlls.Contains(dll)
                     )
                    continue;

                IntPtr ptr = NativeMethods.LoadLibraryW(path);
                if (ptr == IntPtr.Zero)
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    sb.AppendLine($"{path}库加载失败 (错误代码: 0x{errorCode:X8})");
                }
            }

            if (sb.Length == 0)
                sb.AppendLine("\n无异常");

            return sb.ToString();
        }

        
    }
}
